<template>
  <div>
    <!-- 顶部 -->
    <el-card>
      <el-row>
        <el-col :span="7" class="top_input">
          <label>用户ID</label>
          <el-input v-model="searchModel.id" placeholder="用户ID"></el-input>
        </el-col>
        <el-col :span="7" class="top_input">
          <label>用户名</label>
          <el-input
            v-model="searchModel.username"
            placeholder="用户名"
          ></el-input>
        </el-col>
        <el-col :span="7" class="top_input">
          <label>电话号码</label>
          <el-input
            v-model="searchModel.phoneNumber"
            placeholder="电话号码"
          ></el-input>
        </el-col>
      </el-row>

      <div style="margin-left: 5px">
        <el-button type="primary" plain size="small" @click="getUsers"
          >搜索</el-button
        >

        <el-button type="primary" plain size="small" @click="openDig(null)"
          >注册用户</el-button
        >
      </div>
    </el-card>

    <!-- 用户展示区域 -->
    <el-card class="box-card">
      <el-table :data="userList" style="width: 100%" v-loading="loading">
        <el-table-column prop="username" label="用户名" width="180">
        </el-table-column>
        <el-table-column prop="phoneNumber" label="电话号码" width="180">
        </el-table-column>
        <el-table-column prop="content" label="简介"> </el-table-column>
        <el-table-column prop="loginTime" label="上次登录时间">
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <span v-if="scope.row.status">
              <el-tag>已启用</el-tag>
            </span>
            <span v-else>
              <el-tag type="danger">已停用</el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column>
          <template slot-scope="scope">
            <el-button @click="openDig(scope.row.id)" type="text" size="small"
              >编辑</el-button
            >
            <el-button
              @click="openpasswordDig(scope.row)"
              type="text"
              size="small"
              >修改密码</el-button
            >
            <el-button type="text" size="small" @click="opendRoleDig(scope.row)"
              >分配角色</el-button
            >
            <el-button
              type="text"
              size="small"
              color="red"
              @click="deleteById(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-pagination
      @current-change="handleCurrentChange"
      :current-page="searchModel.pageNo"
      :page-size="searchModel.pageSize"
      layout="total,  prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- 对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        ref="userFrom"
        :rules="rules"
        :model="userFrom"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="userFrom.username"
            placeholder="请输入用户名"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="phoneNumber">
          <el-input
            v-model="userFrom.phoneNumber"
            placeholder="请输入电话号码"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item label="简介">
          <el-input
            v-model="userFrom.content"
            type="textarea"
            :rows="2"
            placeholder="请输入简介"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户状态">
          <el-switch
            v-model="userFrom.status"
            active-text="启用"
            inactive-text="停用"
            :active-value="true"
            :inactive-value="false"
          >
          </el-switch>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="register">确定</el-button>
          <el-button @click="close()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 修改密码对话框-->
    <el-dialog
      title="修改密码"
      :visible.sync="dialogVisiblePassword"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        :model="passwordFrom"
        :rules="rules"
        ref="passwordFrom"
        label-width="100px"
      >
        <el-form-item label="密码" prop="pass">
          <el-input
            type="password"
            v-model="passwordFrom.pass"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input
            type="password"
            v-model="passwordFrom.checkPass"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="resetPassword()">提交</el-button>
          <el-button @click="closePasswordDig()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="dialogVisibleRole"
      width="30%"
      :before-close="handleCloseRole"
    >
      <el-select v-model="roleId" filterable placeholder="请选择">
        <el-option
          v-for="item in RoleOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeRoleDig()">取 消</el-button>
        <el-button type="primary" @click="setUserRole()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<style>
.top_input {
  margin: 4px;
}
</style>

<script>
import userApi from "@/api/userApi";
import roleApi from "@/api/role";

export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.passwordFrom.checkPass !== "") {
          this.$refs.passwordFrom.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.passwordFrom.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      searchModel: {
        pageNo: 1,
        pageSize: 10,
      },
      total: 0,

      userList: [],
      // 对话框
      title: "添加用户",
      dialogVisible: false,
      // 是添加还是修改
      model: true,

      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],

        phoneNumber: [{ required: true, message: "电话不能为空" }],

        roleId: [{ required: true, message: "请选择角色", trigger: "change" }],
        pass: [{ required: true, validator: validatePass, trigger: "blur" }],
        checkPass: [
          { required: true, validator: validatePass2, trigger: "blur" },
        ],
      },

      userFrom: {},
      // 修改密码对话框
      dialogVisiblePassword: false,
      passwordFrom: {
        pass: "",
        checkPass: "",
      },

      // 权限图片
      dialogVisibleRole: false,
      roleId: "",
      RoleOptions: [],
      // 加载
      loading: false,
    };
  },

  methods: {
    // 关闭对话框
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.close();
          done();
        })
        .catch((_) => {});
    },
    handleCloseRole() {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.closeRoleDig();
          done();
        })
        .catch((_) => {});
    },

    close() {
      this.userFrom = {};
      // 表单验证
      this.$refs["userFrom"].resetFields();
      this.dialogVisible = false;
    },

    closePasswordDig() {
      this.$refs["passwordFrom"].resetFields();
      this.dialogVisiblePassword = false;
    },

    // 分页
    handleCurrentChange(val) {
      if (val != undefined || val != null) {
        this.pageNo = val;
      }
      this.getUsers();
    },
    getUsers() {
      this.loading = true;
      userApi.getUserList(this.searchModel).then((resp) => {
        this.userList = resp.data.users;
        this.total = resp.data.total;
        this.loading = false;
      });
    },
    register() {
      this.loading = true;
      this.$refs["userFrom"].validate((valid) => {
        if (valid) {
          if (this.model) {
            userApi.update(this.userFrom).then((resp) => {
              this.getUsers();

              this.close();

              this.$message({
                message: "修改成功",
                type: "success",
              });
              this.loading = false;
            });
          } else {
            // 判断是修改用户还是添加用户
            userApi.register(this.userFrom).then((resp) => {
              this.getUsers();
              this.$message({
                message: "注册成功",
                type: "success",
              });
              this.close();
              this.loading = false;
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    openDig(id) {
      if (id) {
        userApi.getById(id).then((resp) => {
          this.title = "修改用户";
          this.userFrom = resp.data;
          this.model = true;
          this.dialogVisible = true;
        });
      } else {
        this.model = false;
        this.title = "注册用户";
        this.dialogVisible = true;
      }
    },

    openpasswordDig(row) {
      this.passwordFrom.id = row.id;
      this.dialogVisiblePassword = true;
    },

    resetPassword() {
      this.$refs["passwordFrom"].validate((valid) => {
        if (valid) {
          let userFrom = {
            id: this.passwordFrom.id,
            password: this.passwordFrom.pass,
          };
          this.loading = true;
          userApi.updatePass(userFrom).then((resp) => {
            this.getUsers();
            this.$message({
              message: "修改成功",
              type: "success",
            });
            this.closePasswordDig();
            this.loading = false;
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 删除用户
    deleteById(id) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loading = true;
          userApi.deleteById(id).then(() => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });

            this.getUsers();
            this.loading = false;
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 查询权限列表
    getRoleList() {
      this.loading = true;
      roleApi.getRoleListByUserSelect().then((resp) => {
        this.RoleOptions = resp.data;
        this.loading = false;
      });
    },

    // 打开分配权限对话框
    opendRoleDig(user) {
      // 回显数据
      this.loading = true;
      userApi.getUserRole(user.id).then((resp) => {
        if (resp.data !== null && resp.data != undefined) {
          this.roleId = resp.data.roleId + "";
        }
        this.userFrom = user;
        this.dialogVisibleRole = true;
        this.loading = false;
      });
    },

    closeRoleDig() {
      this.userFrom = {};
      this.dialogVisibleRole = false;
      this.roleId = "";
    },

    // 这是用户权限
    setUserRole() {
      const userRole = {
        userId: this.userFrom.id,
        roleId: this.roleId,
      };
      this.loading = true;
      userApi.setUserRole(userRole).then((resp) => {
        this.$message({
          type: "success",
          message: resp.message,
        });
        this.closeRoleDig();
        this.loading = false;
      });
    },
  },

  created() {
    this.getUsers();

    this.getRoleList();
  },
};
</script>
